package tv.youxing.android.ui;

import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dou361.ijkplayer.APP.PlayerBackImp;
import com.dou361.ijkplayer.bean.VideoijkBean;
import com.dou361.ijkplayer.listener.OnShowThumbnailListener;
import com.dou361.ijkplayer.widget.PlayStateParams;
import com.dou361.ijkplayer.widget.PlayerView;
import com.example.androidemojidemo.ParseEmojiMsgUtil;
import com.example.androidemojidemo.SelectFaceHelper;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;
import com.kymjs.rxvolley.toolbox.Loger;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.OnekeyShareTheme;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import de.hdodenhof.circleimageview.CircleImageView;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.youxing.android.Interface.LoadMoreListener;
import tv.youxing.android.Interface.UpRefUpdateListener;
import tv.youxing.android.R;
import tv.youxing.android.adapter.AlbumVideoBatchDownloadAllManagerAdapter;
import tv.youxing.android.adapter.VideoPingLunAdapter;
import tv.youxing.android.application.BaseApplication;
import tv.youxing.android.custom.CustomDialog;
import tv.youxing.android.custom.CustomToast;
import tv.youxing.android.custom.Custom_up_down_refresh_ListView;
import tv.youxing.android.entity.CollectionModel;
import tv.youxing.android.entity.DianZhanModel;
import tv.youxing.android.entity.DownloadInfoModel;
import tv.youxing.android.entity.HomeModel;
import tv.youxing.android.entity.SendPingLunModel;
import tv.youxing.android.entity.TuiJianVideoModel;
import tv.youxing.android.entity.VideoPlayerModel;
import tv.youxing.android.entity.VideoPlayerPostModel;
import tv.youxing.android.entity.ViewPlayerPingLunModel;
import tv.youxing.android.ui.test.test3DownloadListener;
import tv.youxing.android.utils.AppConst;
import tv.youxing.android.utils.GsonUtils;
import tv.youxing.android.utils.L;
import tv.youxing.android.utils.MediaUtils;
import tv.youxing.android.utils.PicassoUtils;
import tv.youxing.android.utils.ShareUtils;
import tv.youxing.android.utils.StaticClass;
import tv.youxing.android.utils.UtilTools;

import static com.mob.MobSDK.getContext;
import static tv.youxing.android.R.id.download;

/**
 * 视频播放页面
 */
public class SubscribeDeteilsActivity extends AppCompatActivity implements View.OnClickListener {


    Custom_up_down_refresh_ListView lv;

    private View vHead;
    //播放地址
    String player_uri = "http://youxingshiting.oss-cn-shanghai.aliyuncs.com/cont-1092844-10532190-hd.mp4";
    PlayerView player;


    TextView tvTitle;
    TextView tvTime;
    CircleImageView iv_user_head;
    TextView tvUserName;
    TextView tvDy;
    TextView tvShare;
    TextView tvLove;
    TextView tvCh;
    TextView tvDownload;
    LinearLayout ll_download_state;
    GifImageView gif_download_state;
    GifDrawable mGifDrawable;
    TextView tv_download_state;


    TextView tvPlCount;//评论数量

    TextView tvTuiJianNoLogin;//没登陆不显示相关推荐
    RecyclerView mRelatedRecommendationsRecyclerView;//相关推荐水平滚动列表
    XiangGuanTuiJianAdapter mXiangGuanTuiJianAdapter;


    EditText et_post_conte;//发表内容
    ImageView iv_biaoqing;//发表表情
    TextView tv_send;

    int curLikeCount = 0;//当前的点赞数


    int multimedia_id = -1;//请求视频地址的id值
    private VideoPlayerModel mMain_AllData;//主数据
    private ViewPlayerPingLunModel mViewPlayerPingLunModel;//评论数据
    private List<ViewPlayerPingLunModel.ResultBean.DataBean> mPinglunListData = new ArrayList<>();//评论列表数据


    private TuiJianVideoModel mTuiJianVideoModel;//推荐视频
    private List<TuiJianVideoModel.ResultBean.DataBean> mTuiJianVideoLists = new ArrayList<>();

    int curPingLunCount = -1;//临时的评论数量

    HomeModel.ResultBean.PopularVideoBean.ContListBean newsVideoInfoModelAllData;


    SendPingLunModel mSendPingLunModel;//发表评论
    private VideoPlayerPostModel mAllData;
    DownloadInfoModel apk;

    private PowerManager.WakeLock wakeLock;
    View rootView;
    private VideoPingLunAdapter mPingLunAdapter;


    //当前评论页面
    private int pinglunCurPagePos = 0;


    private CustomDialog mDialog_share;//分享
    private ImageButton wx_btn_share;
    private ImageButton wxpy_btn_share;
    private ImageButton youxing_btn_share;
    private ImageButton qq_btn_share;
    private ImageButton weibo_btn_share;
    private ImageButton copy_btn_share;
    private TextView cancel_btn_share;

    private KProgressHUD hud;

    private boolean isFulllScreen = false;

    private boolean isSubscribe = false;


    //    private SelectFaceHelper mFaceHelper;
    private Button mFaceBtn;
    //    private View addFaceToolView;
//    private boolean isVisbilityFace;
    private EditText mEditMessageEt;


    NumberFormat numberFormat = NumberFormat.getPercentInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        if (UtilTools.checkDeviceHasNavigationBar(this) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
            getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
                @Override
                public void onSystemUiVisibilityChange(int visibility) {
                    int uiOptions =
                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
                    if (Build.VERSION.SDK_INT >= 19) {
                        uiOptions |= 0x00001000;
                    } else {
                        uiOptions |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
                    }
                    getWindow().getDecorView().setSystemUiVisibility(uiOptions);
                }
            });
        } else {

        }



        Bundle bundle = getIntent().getExtras();

        mAllData = (VideoPlayerPostModel) bundle.getSerializable("data");


        numberFormat.setMinimumFractionDigits(2);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);


        //CPU常转
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);


        curPingLunCount = Integer.parseInt(mAllData.getComment_count());

        apk = new DownloadInfoModel();


        apk.name = mAllData.getTitle();
        apk.iconUrl = mAllData.getCover();
        apk.url = mAllData.getPlay_url();
//        apk.iconUrl = "http://img.jsqq.net/uploads/allimg/150111/1_150111080328_19.jpg";
        //http://video.jiecao.fm/11/23/xin/%E5%81%87%E4%BA%BA.mp4
//        apk.url = "http://video.jiecao.fm/11/23/xin/%E5%81%87%E4%BA%BA.mp4";
        apk.playerCount = mAllData.getPlay_count() + "";
        apk.commonCount = mAllData.getComment_count() + "";
        apk.duration = mAllData.getDuration() + "";


        /**常亮*/
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "liveTAG");
        wakeLock.acquire();

//        apk.iconUrl = "http://file.market.xiaomi.com/thumbnail/PNG/l114/AppStore/0c10c4c0155c9adf1282af008ed329378d54112ac";
//        apk.url = "http://121.29.10.1/f5.market.mi-img.com/download/AppStore/0b8b552a1df0a8bc417a5afae3a26b2fb1342a909/com.qiyi.video.apk";
//        Intent intent = getIntent();
//        Bundle bundle = intent.getExtras();
//        System.out.println(bundle.get("playurl"));
//


        //手动设置屏幕亮度 需要权限
//        setScrennManualMode();
//        setWindowBrightness(255);

        new_Load();
    }


//    @Override
//    public void onWindowFocusChanged(boolean hasFocus) {
//        super.onWindowFocusChanged(hasFocus);
//        if( hasFocus ) {
//            hideNavigationBar();
//        }
//    }
//
//
//    private void hideNavigationBar() {
//        final View decorView = getWindow().getDecorView();
////        final int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
////                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
////                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
////                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
////                | View.SYSTEM_UI_FLAG_FULLSCREEN
////                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
//
//
//        final int flags =
//                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
//        decorView.setSystemUiVisibility(flags);
//        decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
//            @Override
//            public void onSystemUiVisibilityChange(int visibility) {
//                if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
//                    decorView.setSystemUiVisibility(flags);
//                }
//            }
//        });
//    }


    private void initFindView() {

//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
//
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);

//        initWindow();
        rootView = getLayoutInflater().from(this).inflate(R.layout.activity_subscribe_deteils, null);
        setContentView(rootView);
        vHead = View.inflate(this, R.layout.subscribedeteils_headview, null);
//        AndroidBug5497Workaround.assistActivity(this);
        initShareDialog();

//        /**虚拟按键的隐藏方法*/
//        rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//
//            @Override
//            public void onGlobalLayout() {
//
//                //比较Activity根布局与当前布局的大小
//                int heightDiff = rootView.getRootView().getHeight() - rootView.getHeight();
//                if (heightDiff > 100) {
//                    //大小超过100时，一般为显示虚拟键盘事件
//                    rootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
//                } else {
//                    //大小小于100时，为不显示虚拟键盘或虚拟键盘隐藏
//                    rootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
//
//                }
//            }
//        });

        tvTitle = (TextView) vHead.findViewById(R.id.tv_title);
        tvTime = (TextView) vHead.findViewById(R.id.time);
        iv_user_head = (CircleImageView) vHead.findViewById(R.id.iv_user_head);
        tvUserName = (TextView) vHead.findViewById(R.id.user_name);
        tvDy = (TextView) vHead.findViewById(R.id.tv_dy);
        tvShare = (TextView) vHead.findViewById(R.id.share);
        tvLove = (TextView) vHead.findViewById(R.id.tv_love);
        tvCh = (TextView) vHead.findViewById(R.id.tv_ch);
        tvDownload = (TextView) vHead.findViewById(download);
        ll_download_state = vHead.findViewById(R.id.ll_download_state);
        gif_download_state = vHead.findViewById(R.id.download_gif);
        mGifDrawable = (GifDrawable) gif_download_state.getDrawable();
        tv_download_state = vHead.findViewById(R.id.tv_download_state);


        lv = (Custom_up_down_refresh_ListView) findViewById(R.id.lv);
        tvPlCount = (TextView) vHead.findViewById(R.id.pl_count);
        tvTuiJianNoLogin = vHead.findViewById(R.id.tjvideo_login_tv);
        mRelatedRecommendationsRecyclerView = vHead.findViewById(R.id.relatedrecommendationsrecyclerView);

//        addFaceToolView = (View) findViewById(R.id.add_tool);
        mEditMessageEt = (EditText) findViewById(R.id.txtMessage);
        mFaceBtn = (Button) findViewById(R.id.btn_to_face);
        mFaceBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UtilTools.getString(mEditMessageEt).length() > 0) {
                    String msgStr = ParseEmojiMsgUtil.convertToMsg(mEditMessageEt.getText(), SubscribeDeteilsActivity.this);// 这里不要直接用mEditMessageEt.getText().toString();
                    showDialog(msgStr, 2);
                } else {
                    showDialog("", 2);
                }
            }
        });

        mEditMessageEt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (UtilTools.getString(mEditMessageEt).length() > 0) {
                    String msgStr = ParseEmojiMsgUtil.convertToMsg(mEditMessageEt.getText(), SubscribeDeteilsActivity.this);// 这里不要直接用mEditMessageEt.getText().toString();
                    showDialog(msgStr, 1);
                } else {
                    showDialog("", 1);
                }
            }
        });


//        mEditMessageEt.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                isVisbilityFace = false;
//                addFaceToolView.setVisibility(View.GONE);
//                return false;
//            }
//        });
//
//        mEditMessageEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
//                if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_SEND) {
//                    String msg = mEditMessageEt.getText().toString();
//                    if (!msg.equals("")) {
//                        String msgStr = ParseEmojiMsgUtil.convertToMsg(mEditMessageEt.getText(), SubscribeDeteilsActivity.this);// 这里不要直接用mEditMessageEt.getText().toString();
//                        sendPingLun(msgStr);
//                        mEditMessageEt.setText("");
//                    }
//                }
//                return true;
//            }
//        });

        iv_user_head.setOnClickListener(this);
        tvDy.setOnClickListener(this);
        tvShare.setOnClickListener(this);
        tvLove.setOnClickListener(this);
        tvCh.setOnClickListener(this);
        tvDownload.setOnClickListener(this);
        ll_download_state.setOnClickListener(this);

        final int paddingBottom = dip2px(this, 5);

    }


    private SelectFaceHelper mFaceHelper;
    private View addFaceToolView;
    private boolean isVisbilityFace;

    private Button dialog_FaceBtn;
    private EditText dialog_edittext;




    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    /**
     * 输入的dialog
     *
     * @param content 输入的内容
     * @param state   区分点击输入法还是表情
     */
    void showDialog(String content, int state) {
        WindowManager wm = this.getWindowManager();

        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();


        final Dialog dialog = new Dialog(this, R.style.softInputDialogStyle);
        View view = View.inflate(this, R.layout.dialog_evaluate, null);


        /**
         * 按下了返回键
         */
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 && event.getAction() == KeyEvent.ACTION_UP) {

                    //L.d("返回键");

                }
                return false;
            }
        });

        /**
         * 消失了
         */
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                if (UtilTools.getString(dialog_edittext).length() > 0) {
//                    mEditMessageEt.setText(UtilTools.getString(dialog_edittext));
                    String msgStr = ParseEmojiMsgUtil.convertToMsg(dialog_edittext.getText(), SubscribeDeteilsActivity.this);// 这里不要直接用mEditMessageEt.getText().toString();
                    mEditMessageEt.setText(msgStr);

                }

                if (isVisbilityFace) {
                    isVisbilityFace = false;
                    addFaceToolView.setVisibility(View.GONE);
                }
            }
        });


        addFaceToolView = (View) view.findViewById(R.id.add_tool);
        dialog_edittext = (EditText) view.findViewById(R.id.txtMessage);
        dialog_FaceBtn = (Button) view.findViewById(R.id.btn_to_face);
        dialog_FaceBtn.setOnClickListener(faceClick);
        dialog_edittext.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                isVisbilityFace = false;
                addFaceToolView.setVisibility(View.GONE);
                return false;
            }
        });


        dialog_edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_SEND) {
                    String msg = dialog_edittext.getText().toString();
                    if (!msg.equals("")) {
                        String msgStr = ParseEmojiMsgUtil.convertToMsg(dialog_edittext.getText(), SubscribeDeteilsActivity.this);// 这里不要直接用mEditMessageEt.getText().toString();
                        dialog_edittext.setText("");
                        mEditMessageEt.setText("");
                        sendPingLun(msgStr);
                        //发送评论
                    }
                }
                return true;
            }
        });




//        Button button = (Button) view.findViewById(R.id.evaluate_send);
        //设置对话框的风格
        dialog.setCanceledOnTouchOutside(true);
//        view.setMinimumHeight((int) (height * 0.2f));//对话框最小值
        dialog.setContentView(view);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = width;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);
        dialog.show();


        if (state == 1) {
//                    Timer timer = new Timer();
//        timer.schedule(new TimerTask() {
//
//            @Override
//            public void run() {
//                showKeyboard();
//            }
//        }, 200);


            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                   showKeyboard();
                }
            },200);
        }



        hideBottomUIMenu();


        if (state == 1) {

        } else if (state == 2) {
            faceClick();
        }


        if (content != null || content.length() > 0) {
            dialog_edittext.setText(content);
        }
    }


    public void showKeyboard() {
        if(dialog_edittext!=null){
            //设置可获得焦点
            dialog_edittext.setFocusable(true);
            dialog_edittext.setFocusableInTouchMode(true);
            //请求获得焦点
            dialog_edittext.requestFocus();
            //调用系统输入法
            InputMethodManager inputManager = (InputMethodManager) dialog_edittext
                    .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(dialog_edittext, 0);
        }
    }


    SelectFaceHelper.OnFaceOprateListener mOnFaceOprateListener = new SelectFaceHelper.OnFaceOprateListener() {
        @Override
        public void onFaceSelected(SpannableString spanEmojiStr) {
            if (null != spanEmojiStr) {
                dialog_edittext.append(spanEmojiStr);
            }
        }

        @Override
        public void onFaceDeleted() {
            int selection = dialog_edittext.getSelectionStart();
            String text = dialog_edittext.getText().toString();
            if (selection > 0) {
                String text2 = text.substring(selection - 1);
                if ("]".equals(text2)) {
                    int start = text.lastIndexOf("[");
                    int end = selection;
                    dialog_edittext.getText().delete(start, end);
                    return;
                }
                dialog_edittext.getText().delete(selection - 1, selection);
            }
        }

    };


    View.OnClickListener faceClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            faceClick();
        }
    };


    void faceClick() {
        hideInputManager(this);
        if (mFaceHelper != null) {
            mFaceHelper = null;
        }


        if (null == mFaceHelper) {
            mFaceHelper = new SelectFaceHelper(SubscribeDeteilsActivity.this, addFaceToolView);
            mFaceHelper.setFaceOpreateListener(mOnFaceOprateListener);
        }
        if (isVisbilityFace) {
            isVisbilityFace = false;
            addFaceToolView.setVisibility(View.GONE);

        } else {
            isVisbilityFace = true;
            addFaceToolView.setVisibility(View.VISIBLE);
            hideInputManager(this);
        }



    }

    private boolean hideKeyboard(){
        InputMethodManager inputMethodManager = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if(inputMethodManager.isActive(dialog_edittext)){//因为是在fragment下，所以用了getView()获取view，也可以用findViewById（）来获取父控件
            dialog_edittext.requestFocus();//使其它view获取焦点.这里因为是在fragment下,所以便用了getView(),可以指定任意其它view
            inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            return true;
        }
        return false;
    }


    public int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private void setOnClickListener() {

        /**
         * 上拉加载更多
         */
        lv.setLoadMoreListener(new LoadMoreListener() {
            @Override
            public void onLoadMore() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initPingLunData(mAllData.getMultimedia_id(), new UpRefUpdateListener() {
                            @Override
                            public void upRef(int count) {
                                if (count > 0) {
                                    L.d("loadMoreComplete");
                                    lv.loadMoreComplete();
                                } else {
                                    L.d("loadMoreEnd");
                                    lv.loadMoreEnd();
                                }
                            }
                        });

//
                    }
                }, 1500);

            }
        });
    }


    private void initShareDialog() {
        mDialog_share = new CustomDialog(SubscribeDeteilsActivity.this, ViewGroup.LayoutParams.MATCH_PARENT
                , ViewGroup.LayoutParams.WRAP_CONTENT, R.layout.share_layout, R.style.Theme_dialog, Gravity.BOTTOM, R.style.pop_anim_style);
        mDialog_share.setCancelable(true);

        mDialog_share.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                if (player != null) {
//                    player.startPlay();
                }
            }
        });

        wx_btn_share = (ImageButton) mDialog_share.findViewById(R.id.wx);
        wxpy_btn_share = (ImageButton) mDialog_share.findViewById(R.id.wxpy);
        youxing_btn_share = (ImageButton) mDialog_share.findViewById(R.id.youxing);
        qq_btn_share = (ImageButton) mDialog_share.findViewById(R.id.qq);
        weibo_btn_share = (ImageButton) mDialog_share.findViewById(R.id.weibo);
        copy_btn_share = (ImageButton) mDialog_share.findViewById(R.id.copy);
        cancel_btn_share = mDialog_share.findViewById(R.id.cancel);

        wx_btn_share.setOnClickListener(this);
        wxpy_btn_share.setOnClickListener(this);
        youxing_btn_share.setOnClickListener(this);
        qq_btn_share.setOnClickListener(this);
        weibo_btn_share.setOnClickListener(this);
        copy_btn_share.setOnClickListener(this);
        cancel_btn_share.setOnClickListener(this);
    }




    void new_Load() {
        initFindView();
        initPingLunList();
        setOnClickListener();

//        initVideo(mAllData.getPlay_url());
        initPingLunData(mAllData.getMultimedia_id(), null);
        initTuiJianVideo(mAllData.getMultimedia_id());
        initData();


//        videoDownload();


    }

    void used_Load() {
        this.multimedia_id = Integer.parseInt(getIntent().getStringExtra("multimedia_id"));
        if (multimedia_id == -1) {
            finish();
            CustomToast.INSTANCE.showToast("播放出错，可能是 id 有误");
        } else {
            initFindView();
            loadData(null);
        }
    }

    /**
     * 发送评论
     */
    void sendPingLun(final String str) {

        if (!UtilTools.LoginJudge()) {
            CustomToast.INSTANCE.showToast("请先登录");
            return;
        }

        //post请求简洁版实现
        HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(this, AppConst.TOKEN, ""));
        params.put("content", str);
        params.put("resource_type", 1);
        params.put("resource_id", mAllData.getMultimedia_id());

        RxVolley.post(StaticClass.SendPingLun, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                mSendPingLunModel = GsonUtils.GsonToBean(t, SendPingLunModel.class);

                if (mSendPingLunModel.getCode() == AppConst.TOKENERROR) {
                    SubscribeDeteilsActivity.this.startActivity(new Intent(SubscribeDeteilsActivity.this,LoginActivity.class));
                    return;
                }

                if (mSendPingLunModel.getCode() == 200) {
                    System.out.println(t);
                    CustomToast.INSTANCE.showToast("发表成功");
//                    ViewPlayerPingLunModel.ResultBean.DataBean model = new ViewPlayerPingLunModel.ResultBean.DataBean();
//                    model.setContent(str);
//                    mPinglunListData.add(model);

                    tvPlCount.setText("评论 (" + (curPingLunCount + 1) + ")");

                    pinglunCurPagePos = 0;
                    mPinglunListData.clear();
                    lv.refreshComplete();
                    initPingLunList();
                    initPingLunData(mAllData.getMultimedia_id(), null);

                    ViewPlayerPingLunModel.ResultBean.DataBean dataBean = new ViewPlayerPingLunModel.ResultBean.DataBean();
                    dataBean.setContent(str);
                    dataBean.setResource_type(1);
                    dataBean.setResource_id(mAllData.getMultimedia_id());
                    ViewPlayerPingLunModel.ResultBean.DataBean.PublishUserBean publishUserBean = new ViewPlayerPingLunModel.ResultBean.DataBean.PublishUserBean();
                    publishUserBean.setUsername(ShareUtils.getString(getContext(), AppConst.USERNAME, ""));
                    publishUserBean.setAvatar(ShareUtils.getString(getContext(), AppConst.AVATER, ""));
                    dataBean.setPublish_user(publishUserBean);
//                    dataBean.setIs_like(0);
                    dataBean.setUpdated_at(UtilTools.getCurTime());

//                    mPinglunListData.add(dataBean);
//                    updatePingList();
                    L.d("avater:" + ShareUtils.getString(getContext(), AppConst.AVATER, ""));


                } else {
                    CustomToast.INSTANCE.showToast("发表失败");
                }
            }
        });
    }

    private void loadData(UpRefUpdateListener listener) {
        //请求主数据
        HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(this, AppConst.TOKEN, ""));
        params.put("multimedia_id", this.multimedia_id);

        RxVolley.post(StaticClass.VideoPlayerUrl, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                mMain_AllData = GsonUtils.GsonToBean(t, VideoPlayerModel.class);

                if (mMain_AllData.getCode() == AppConst.TOKENERROR) {
                    SubscribeDeteilsActivity.this.startActivity(new Intent(SubscribeDeteilsActivity.this,LoginActivity.class));
                    return;
                }

                initData();
            }
        });
    }


    /**
     * 评论列表数据
     */
    void initPingLunData(int id, final UpRefUpdateListener listener) {

        pinglunCurPagePos++;


//        L.d("resource_id:" + id);


        //请求评论数据
        HttpParams params = new HttpParams();
        params.put("resource_type", 1);
        params.put("resource_id", id);
        params.put("page", pinglunCurPagePos);
        if (UtilTools.LoginJudge()) {
            params.put("user_id", ShareUtils.getInt(getContext(), AppConst.USERID, 0));
        }


        L.d("resource_id:" + id);
        L.d("user_id:" + ShareUtils.getInt(getContext(), AppConst.USERID, 0));


        RxVolley.post(StaticClass.VideoPlayerPingLunUrl, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                mViewPlayerPingLunModel = GsonUtils.GsonToBean(t, ViewPlayerPingLunModel.class);
                if (mViewPlayerPingLunModel.getCode() == 200) {


                    for (int i = 0; i < mPinglunListData.size(); i++) {

                        L.d(mPinglunListData.get(i).getContent());

                    }

                    mPinglunListData.addAll(mViewPlayerPingLunModel.getResult().getData());
                    mPingLunAdapter.notifyDataSetChanged();

                    if (listener != null) {

                        L.d("load succ");

                        listener.upRef(mViewPlayerPingLunModel.getResult().getData().size());
                    }

                } else {
                    L.d("load error");
                }
            }
        });
    }


    /**
     * 推荐视频
     */
    void initTuiJianVideo(int multimedia_id) {
            HttpParams params = new HttpParams();
            params.put("multimedia_id", multimedia_id);
            params.put("user_id", ShareUtils.getInt(this, AppConst.USERID, 0));

            RxVolley.post(StaticClass.TuiJianVideoURL, params, new HttpCallback() {
                @Override
                public void onSuccess(String t) {
                    mTuiJianVideoModel = GsonUtils.GsonToBean(t, TuiJianVideoModel.class);
                    if (mTuiJianVideoModel.getCode() == 200) {


                        mTuiJianVideoLists = mTuiJianVideoModel.getResult().getData();

                        if (mTuiJianVideoLists.size() <= 0) {
                            mRelatedRecommendationsRecyclerView.setVisibility(View.GONE);
                            tvTuiJianNoLogin.setVisibility(View.VISIBLE);
                            tvTuiJianNoLogin.setText("暂无推荐(～ o ～)~zZ");
                        } else {
                            initXiangGuanTuiJianListView();
                        }
                    } else {
                        L.d("error:" + t);
                    }
                }
            });
    }

    /**
     * 初始化视频
     */
    void initVideo(String url) {

        player = new PlayerView(this) {
            @Override
            public PlayerView toggleProcessDurationOrientation() {
                hideSteam(getScreenOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                return setProcessDurationOrientation(getScreenOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ? PlayStateParams.PROCESS_PORTRAIT : PlayStateParams.PROCESS_LANDSCAPE);
            }

            @Override
            public PlayerView setPlaySource(List<VideoijkBean> list) {
                return super.setPlaySource(list);
            }
        }
                .setTitle(mAllData.getTitle())
                .setScaleType(PlayStateParams.f16_9)
                .hideMenu(true)
                .hideSteam(true)
                .hideCenterPlayer(true)
                .forbidTouch(false)
                .setOnInfoListener(new IMediaPlayer.OnInfoListener() {
                    @Override
                    public boolean onInfo(IMediaPlayer iMediaPlayer, int state, int i1) {
                        if (state == iMediaPlayer.MEDIA_INFO_BUFFERING_END) {
                            //缓冲结束
//                            L.d("缓冲结束");
                        } else if (state == iMediaPlayer.MEDIA_INFO_BUFFERING_START) {
//                            L.d("开始缓冲");
                        }
                        return false;
                    }
                })
                .showThumbnail(new OnShowThumbnailListener() {
                    @Override
                    public void onShowThumbnail(ImageView ivThumbnail) {
                        /**加载前显示的缩略图*/
//                        Glide.with(mContext)
//                                .load("http://pic2.nipic.com/20090413/406638_125424003_2.jpg")
//                                .placeholder(R.color.cl_default)
//                                .error(R.color.cl_error)
//                                .into(ivThumbnail);
//                                                PicassoUtils.loadImageView(SubscribeDeteilsActivity.this, mAllData.getCover(), ivThumbnail);
//                        ImageLoader.getInstance().displayImage(mAllData.getCover(), ivThumbnail);

                    }
                })
                .setPlaySource(url);
        if (BaseApplication.mVideoPos.containsKey(mAllData.getMultimedia_id())) {
            player.startPlay();
            player.seekTo(BaseApplication.mVideoPos.get(mAllData.getMultimedia_id()));
        } else {
            player.startPlay();
        }

        player.setPlayerBackImp(new PlayerBackImp() {
            @Override
            public void PlayerBack() {
                if (UtilTools.LoginJudge()) {
                    int c = player.getCurrentPosition();

                    if (c > 1000) {
                        ViewinRecord((c / 1000));
                    }

//                L.d((c/1000)+"--数值时");
                }
            }
        });

//        player.setBrightness(Integer.valueOf(getSystemBrightness()/2));





    }

    /**
     *       * 获得系统亮度
     *       *
     *       * @return
     *
     */
    private int getSystemBrightness() {
        int systemBrightness = 0;
        try {
            systemBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return systemBrightness;
    }


    void initData() {
        //列表头数据
        PicassoUtils.loadImageView(this, mAllData.getAlbum().getCover(), iv_user_head);
        tvUserName.setText(mAllData.getAlbum().getName());
        tvTitle.setText(mAllData.getTitle());
        tvTime.setText(mAllData.getPublish_at());






        if (mAllData.getAlbum().getIs_order() == 1) {
            //已订阅
            tvDy.setBackgroundResource(R.mipmap.video_btn_subscribe_pre);
            isSubscribe=true;
        } else {
            //未订阅
            tvDy.setBackgroundResource(R.mipmap.video_btn_subscribe_nor);
            isSubscribe=false;
        }

        curLikeCount = Integer.parseInt(mAllData.getLike_count());
        tvLove.setText("点赞 " + curLikeCount);
        if (mAllData.getIs_like() == 1) {
            tvLove.setSelected(true);
        } else {
            tvLove.setSelected(false);
        }


        //判断是否收藏
        if (mAllData.getIs_collectied() == 1) {
            tvCh.setSelected(true);
        } else {
            tvCh.setSelected(false);
        }


        tvPlCount.setText("评论 (" + mAllData.getComment_count() + ")");


        //判断视频是否在下载

        DownloadTask downloadTask = OkDownload.getInstance().getTask(apk.url);


        if (downloadTask != null) {


            tvDownload.setVisibility(View.GONE);
            ll_download_state.setVisibility(View.VISIBLE);

//            tvDownload.setText("已加入");
//            tvDownload.setSelected(true);
//            tvDownload.setText("已暂停");

            downloadTask.register(new DownloadListener(apk.name) {
                @Override
                public void onStart(Progress progress) {

                }

                @Override
                public void onProgress(Progress progress) {
//                    tvDownload.setText("正在下载:" + (numberFormat.format(progress.fraction)));


                    refresh(progress);

//                    System.out.println("当前状态2:" + progress.status);

                }

                @Override
                public void onError(Progress progress) {
                    tv_download_state.setText("下载出错");
                }

                @Override
                public void onFinish(File file, Progress progress) {
                    tv_download_state.setText("下载完成");
                }

                @Override
                public void onRemove(Progress progress) {

                }
            });

            refresh(downloadTask.progress);
        } else {

            tvDownload.setVisibility(View.VISIBLE);
            ll_download_state.setVisibility(View.GONE);

            tvDownload.setText("下载");
            tvDownload.setSelected(false);
        }


        initVideo(mAllData.getPlay_url());
    }


    /**
     * 评论列表
     */
    boolean is_one_load = false;

    void initPingLunList() {
        mPingLunAdapter = new VideoPingLunAdapter(this, mPinglunListData);
        if (!is_one_load) {
            lv.addHeaderView(vHead);
            is_one_load = true;
        }
        lv.setAdapter(mPingLunAdapter);
    }

    /**
     * 更新评论列表
     */
    void updatePingList() {
        mPingLunAdapter.notifyDataSetChanged();
    }


    /**
     * 相关推荐列表
     */
    void initXiangGuanTuiJianListView() {
        mXiangGuanTuiJianAdapter = new XiangGuanTuiJianAdapter(mTuiJianVideoLists, getContext());
        LinearLayoutManager ms = new LinearLayoutManager(getContext());
        ms.setOrientation(LinearLayoutManager.HORIZONTAL);// 设置 recyclerview 布局方式为横向布局
        mRelatedRecommendationsRecyclerView.setLayoutManager(ms);
        mRelatedRecommendationsRecyclerView.setAdapter(mXiangGuanTuiJianAdapter);
    }

    /**
     * 请求用户信息
     */
    void initUserInfo() {
        //post请求简洁版实现
        HttpParams params = new HttpParams();

        RxVolley.post("http://kymjs.com/feed.xml", params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                Loger.debug("请求到的数据:" + t);
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (player != null) {
//            BaseApplication.current_Pos = player.getCurrentPosition();
//            BaseApplication.mVideoPos.put(mAllData.getMultimedia_id(), player.getCurrentPosition());
            player.onPause();
        }


        /**demo的内容，恢复系统其它媒体的状态*/
        MediaUtils.muteAudioFocus(getContext(), true);

        if (BaseApplication.mNewsPlay != null) {
            BaseApplication.mNewsPlay = null;
        }

        //最后一次的播放记录 配合中间的小按钮
        VideoPlayerPostModel m = mAllData;
        BaseApplication.mNewsPlay = new VideoPlayerPostModel();
        BaseApplication.mNewsPlay.setMultimedia_id(m.getMultimedia_id());
        BaseApplication.mNewsPlay.setTitle(m.getTitle());
        BaseApplication.mNewsPlay.setIntro(m.getIntro());
        BaseApplication.mNewsPlay.setCover(m.getCover());
        BaseApplication.mNewsPlay.setDuration(m.getDuration());
        BaseApplication.mNewsPlay.setPublish_at(m.getPublish_at());
        BaseApplication.mNewsPlay.setPlay_url(m.getPlay_url());
        BaseApplication.mNewsPlay.setType(m.getType());
        BaseApplication.mNewsPlay.setPlay_count(m.getPlay_count());
        BaseApplication.mNewsPlay.setComment_count(m.getComment_count());
        BaseApplication.mNewsPlay.setLike_count(m.getLike_count());
        BaseApplication.mNewsPlay.setCollection_count(m.getCollection_count());
        BaseApplication.mNewsPlay.setStatus(m.getStatus());
        BaseApplication.mNewsPlay.setCreated_at(m.getCreated_at());
        BaseApplication.mNewsPlay.setUpdated_at(m.getUpdated_at());
        BaseApplication.mNewsPlay.setAlbum_name(m.getAlbum_name());
        VideoPlayerPostModel.AlbumBean albumBean = new VideoPlayerPostModel.AlbumBean();
        albumBean.setAlbum_id(m.getAlbum().getAlbum_id());
        albumBean.setName(m.getAlbum().getName());
        albumBean.setCover(m.getAlbum().getCover());
        albumBean.setIs_order(m.getAlbum().getIs_order());
        BaseApplication.mNewsPlay.setAlbum(albumBean);
    }

    @Override
    protected void onResume() {


        super.onResume();
        if (player != null) {
            player.onResume();
            //player.seekTo(BaseApplication.current_Pos);
        } else {
        }
        /**demo的内容，暂停系统其它媒体的状态*/
        MediaUtils.muteAudioFocus(getContext(), false);
        /**demo的内容，激活设备常亮状态*/
        if (wakeLock != null) {
            wakeLock.acquire();
        }
    }


    private void setWindowBrightness(int brightness) {
        Window window = getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.screenBrightness = brightness / 255.0f;
        window.setAttributes(lp);
    }


    public void setScrennManualMode() {
        ContentResolver contentResolver = this.getContentResolver();
        try {
            int mode = Settings.System.getInt(contentResolver,
                    Settings.System.SCREEN_BRIGHTNESS_MODE);
            if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
                Settings.System.putInt(contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
                        Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            }
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onDestroy() {
        if (player != null) {
            player.onDestroy();
        }
        if (!mGifDrawable.isRecycled()) {
            mGifDrawable.recycle();
        }




        super.onDestroy();
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);


        if (player != null) {
            player.onConfigurationChanged(newConfig);
        }

        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//            Toast.makeText(SubscribeDeteilsActivity.this, "现在是竖屏", Toast.LENGTH_SHORT).show();
        }
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//            Toast.makeText(SubscribeDeteilsActivity.this, "现在是横屏", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onBackPressed() {
        if (player != null && player.onBackPressed()) {
            return;
        }

        if (player != null) {
            if (UtilTools.LoginJudge()) {
                int c = player.getCurrentPosition();

                if (c > 1000) {
                    ViewinRecord((c / 1000));
                }

//                L.d((c/1000)+"--数值时");
            }
        }

        super.onBackPressed();
        /**demo的内容，恢复设备亮度状态*/
        if (wakeLock != null) {
            wakeLock.release();
        }


    }


    //视频观看记录
    public void ViewinRecord(int play_time) {
        HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));
        params.put("resource_id", mAllData.getMultimedia_id());
        params.put("resource_type", 1);
        params.put("play_time", play_time);


        RxVolley.post(StaticClass.VideoviewingRecord, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                DianZhanModel dianZhanModel = GsonUtils.GsonToBean(t, DianZhanModel.class);

                if (dianZhanModel.getCode() == AppConst.TOKENERROR) {
                    SubscribeDeteilsActivity.this.startActivity(new Intent(SubscribeDeteilsActivity.this,LoginActivity.class));
                    return;
                }

                L.d(dianZhanModel.getStatus());
            }
        });
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.iv_user_head://点击用户头像

                if (!UtilTools.LoginJudge()) {
                    CustomToast.INSTANCE.showToast("请先登录");
                    return;
                }


                Intent intent = new Intent(this,DynamicDetailActivity.class);
                intent.putExtra("album_id",mAllData.getAlbum().getAlbum_id()+"");
                startActivity(intent);

                if (player != null) {
                    if (UtilTools.LoginJudge()) {
                        int c = player.getCurrentPosition();

                        if (c > 1000) {
                            ViewinRecord((c / 1000));
                        }

//                L.d((c/1000)+"--数值时");
                    }
                }

                finish();

                break;
            case R.id.tv_dy:
                if (isSubscribe == false) {
                    Subscribe();
                } else {
                    //取消订阅
                    subsctibe_cancel();
                }
                break;
            case R.id.share:
//                                share(this,null, true);
                player.pausePlay();
                mDialog_share.show();
                break;
            case R.id.tv_love://喜欢-点赞
                Like();
                break;
            case R.id.tv_ch://收藏
                Collection();
                break;
            case download:
                videoDownload();
                break;
            case R.id.
                    ll_download_state:
                videoDownload();
                break;

            case R.id.wx:
                share(this, Wechat.NAME, false);
//                Logger.d(mAllData.getVideo_share_url());
                break;
            case R.id.wxpy:
                share(this, WechatMoments.NAME, false);
                break;
            case R.id.youxing:
                //发布到发现里面
                sendDynamics();
                break;
            case R.id.qq:
                share(this, QQ.NAME, false);
                break;
            case R.id.weibo:
                share(this, SinaWeibo.NAME, false);
                break;
            case R.id.copy:
                // 复制到粘贴板
                // 从API11开始android推荐使用android.content.ClipboardManager
                // 为了兼容低版本我们这里使用旧版的android.text.ClipboardManager，虽然提示deprecated，但不影响使用。
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                cm.setText(mAllData.getPlay_url());
                CustomToast.INSTANCE.showToast("复制成功，可以发给朋友们了");
                break;
            case R.id.cancel:
                if (mDialog_share.isShowing()) {
                    mDialog_share.dismiss();

                }
                break;
        }

    }


    /**
     * 发布动态(发布到发现里面)
     */
    private void sendDynamics() {


        if (!UtilTools.LoginJudge()) {
            CustomToast.INSTANCE.showToast("请先登录");
            return;
        }

        HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));

        params.put("content", mAllData.getTitle());
        params.put("image_1", mAllData.getCover());
        params.put("type", 2);
        params.put("resource_id",mAllData.getMultimedia_id());
//        showProgress("发布中");
        RxVolley.post(StaticClass.PublicationDynamics, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                DianZhanModel dianZhanModel = GsonUtils.GsonToBean(t, DianZhanModel.class);

                if (dianZhanModel.getCode() == AppConst.TOKENERROR) {
                    SubscribeDeteilsActivity.this.startActivity(new Intent(SubscribeDeteilsActivity.this,LoginActivity.class));
                    return;
                }

                if (dianZhanModel.getCode() == 200) {
                    CustomToast.INSTANCE.showToast("发布成功");
                } else {
                    System.out.println(t);
                    CustomToast.INSTANCE.showToast("发布失败");
                }
//                hideProgress();
            }
        });
    }


    /**
     * 订阅
     */
    void Subscribe() {

        if (!UtilTools.LoginJudge()) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }


        showProgress("处理中");

        HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));
        params.put("album_id", mAllData.getAlbum().getAlbum_id());

        RxVolley.post(StaticClass.album_order, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                DianZhanModel dianZhanModel = GsonUtils.GsonToBean(t, DianZhanModel.class);

                if (dianZhanModel.getCode() == AppConst.TOKENERROR) {
                    SubscribeDeteilsActivity.this.startActivity(new Intent(SubscribeDeteilsActivity.this,LoginActivity.class));
                    return;
                }

                if (dianZhanModel.getCode() == 200) {
                    CustomToast.INSTANCE.showToast(dianZhanModel.getStatus());
                    tvDy.setBackgroundResource(R.mipmap.video_btn_subscribe_pre);
                    isSubscribe=true;
                    EventBus.getDefault().post("home");
                } else {
                    System.out.println(t);
                    CustomToast.INSTANCE.showToast("订阅失败");
                }

                hideProgress();
            }
        });
    }


    /**
     * 取消订阅
     */
    void subsctibe_cancel() {
        if (!UtilTools.LoginJudge()) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }


        showProgress("处理中");

        HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));
        params.put("album_id", mAllData.getAlbum().getAlbum_id());

        RxVolley.post(StaticClass.album_cancel, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                DianZhanModel dianZhanModel = GsonUtils.GsonToBean(t, DianZhanModel.class);

                if (dianZhanModel.getCode() == AppConst.TOKENERROR) {
                    SubscribeDeteilsActivity.this.startActivity(new Intent(SubscribeDeteilsActivity.this,LoginActivity.class));
                    return;
                }

                if (dianZhanModel.getCode() == 200) {
                    CustomToast.INSTANCE.showToast(dianZhanModel.getStatus());
                    tvDy.setBackgroundResource(R.mipmap.video_btn_subscribe_nor);
                    isSubscribe=false;
                    EventBus.getDefault().post("home");
                } else {
                    System.out.println(t);
                    CustomToast.INSTANCE.showToast("订阅失败");
                }

                hideProgress();
            }
        });
    }

    /**
     * 喜欢
     */
    void Like() {

        if (!UtilTools.LoginJudge()) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }


        showProgress("处理中");

        HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));
        params.put("resource_id", mAllData.getMultimedia_id());
        params.put("resource_type", 1);

        RxVolley.post(StaticClass.DianZan, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                DianZhanModel dianZhanModel = GsonUtils.GsonToBean(t, DianZhanModel.class);

                if (dianZhanModel.getCode() == AppConst.TOKENERROR) {
                    SubscribeDeteilsActivity.this.startActivity(new Intent(SubscribeDeteilsActivity.this,LoginActivity.class));
                    return;
                }

                if (dianZhanModel.getCode() == 200) {
                    if (dianZhanModel.getResult().getIs_like() == 1) {
                        tvLove.setSelected(true);
                        curLikeCount++;
                        tvLove.setText("点赞 " + curLikeCount);
                    } else {
                        tvLove.setSelected(false);
                        if (curLikeCount > 0) {
                            curLikeCount--;
                        }
                        tvLove.setText("点赞 " + curLikeCount);
                    }
                    EventBus.getDefault().post("home");
                } else {
                    System.out.println(t);
                    CustomToast.INSTANCE.showToast("点赞失败");
                    tvLove.setSelected(false);
                }

                hideProgress();
            }
        });
    }

    /**
     * 收藏
     */
    void Collection() {
        if (!UtilTools.LoginJudge()) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }

        showProgress("处理中");

        HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));
        params.put("resource_id", mAllData.getMultimedia_id());
        params.put("resource_type", 1);

        RxVolley.post(StaticClass.ShouChang, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                CollectionModel dianZhanModel = GsonUtils.GsonToBean(t, CollectionModel.class);
                if (dianZhanModel.getCode() == 200) {

                    if (dianZhanModel.getCode() == AppConst.TOKENERROR) {
                        SubscribeDeteilsActivity.this.startActivity(new Intent(SubscribeDeteilsActivity.this,LoginActivity.class));
                        return;
                    }

                    if (dianZhanModel.getResult().getIs_collection() == 1) {
                        tvCh.setSelected(true);
                    } else {
                        tvCh.setSelected(false);
                    }
                    EventBus.getDefault().post("home");
                } else {
                    System.out.println(t);
                    CustomToast.INSTANCE.showToast("收藏失败");
                    tvCh.setSelected(false);
                    tvCh.setEnabled(false);
                }
                hideProgress();
            }
        });
    }

    /**
     * 下载
     */
    private void videoDownload() {
        if (!UtilTools.LoginJudge()) {
//            startActivity(new Intent(this,LoginActivity.class));
            CustomToast.INSTANCE.showToast("请先登录");
            return;
        }


        DownloadTask Task = OkDownload.getInstance().getTask(apk.url);

        if (Task != null) {
            start(Task);
        } else {

//        System.out.println("下载地址是:" + apk.url);

            GetRequest<File> request = OkGo.<File>get(apk.url);//
//                .headers("aaa", "111")//
//                .params("bbb", "222");

            //这里第一个参数是tag，代表下载任务的唯一标识，传任意字符串都行，需要保证唯一,我这里用url作为了tag
            OkDownload.request(apk.url, request)//
                    .priority(apk.priority)//
                    .extra1(apk)//
                    .save()
                    .register(new test3DownloadListener())//
                    .start();


            DownloadTask downloadTask = OkDownload.getInstance().getTask(apk.url);
            if (downloadTask != null) {
//            tvDownload.setText("已加入");
//            tvDownload.setSelected(true);
//            tvDownload.setEnabled(false);

                tvDownload.setVisibility(View.GONE);
                ll_download_state.setVisibility(View.VISIBLE);

//
                downloadTask.register(new DownloadListener(apk.name) {
                    @Override
                    public void onStart(Progress progress) {

                    }

                    @Override
                    public void onProgress(Progress progress) {
                        refresh(progress);
                    }

                    @Override
                    public void onError(Progress progress) {
                        tv_download_state.setText("下载出错");
                    }

                    @Override
                    public void onFinish(File file, Progress progress) {
                        tv_download_state.setText("下载完成");
                    }

                    @Override
                    public void onRemove(Progress progress) {

                    }
                });

            }
        }


//        tvDownload.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                //这里只是演示，表示请求可以传参，怎么传都行，和okgo使用方法一样
//                GetRequest<File> request = OkGo.<File>get(apk.url)//
//                        .headers("aaa", "111")//
//                        .params("bbb", "222");
//
//                //这里第一个参数是tag，代表下载任务的唯一标识，传任意字符串都行，需要保证唯一,我这里用url作为了tag
//                OkDownload.request(apk.url, request)//
//                        .priority(apk.priority)//
//                        .extra1(apk)//
//                        .register(new test3DownloadListener())//
//                        .start();
////                adapter.notifyDataSetChanged();
//            }
//        });

    }


    /**
     * 刷新状态
     *
     * @param progress
     */
    public void refresh(Progress progress) {
//        String currentSize = Formatter.formatFileSize(context, progress.currentSize);
//        String totalSize = Formatter.formatFileSize(context, progress.totalSize);
//        downloadSize.setText(currentSize + "/" + totalSize);
//        priority.setText(String.format("优先级：%s", progress.priority));
        switch (progress.status) {
            case Progress.NONE:
//                netSpeed.setText("停止");
//                download.setText("下载");
                tv_download_state.setText("停止");
                if (mGifDrawable.isPlaying()) {
                    mGifDrawable.stop();
                }
                break;
            case Progress.PAUSE:
//                netSpeed.setText("暂停中");
//                download.setText("继续");
                tv_download_state.setText("暂停中");
                if (mGifDrawable.isPlaying()) {
                    mGifDrawable.stop();
                }
                break;
            case Progress.ERROR:
//                netSpeed.setText("下载出错");
//                download.setText("出错");
                tv_download_state.setText("下载出错");
                if (mGifDrawable.isPlaying()) {
                    mGifDrawable.stop();
                }
                break;
            case Progress.WAITING:
//                netSpeed.setText("等待中");
//                download.setText("等待");
                tv_download_state.setText("等待中");
                if (mGifDrawable.isPlaying()) {
                    mGifDrawable.stop();
                }
                break;
            case Progress.FINISH:
//                netSpeed.setText("下载完成");
//                download.setText("完成");
                tv_download_state.setText("下载完成");
                if (mGifDrawable.isPlaying()) {
                    mGifDrawable.stop();
                }
                break;
            case Progress.LOADING:
                tv_download_state.setText((numberFormat.format(progress.fraction)));

                if (!mGifDrawable.isPlaying()) {
                    mGifDrawable.start();
                }
//                String speed = Formatter.formatFileSize(context, progress.speed);
//                netSpeed.setText(String.format("%s/s", speed));
//                download.setText("暂停");
                break;
        }
//        tvProgress.setText(numberFormat.format(progress.fraction));
//            pbProgress.setMax(10000);
//            pbProgress.setProgress((int) (progress.fraction * 10000));
    }

    public void start(DownloadTask task) {
        Progress progress = task.progress;


        switch (progress.status) {
            case Progress.PAUSE:
            case Progress.NONE:
            case Progress.ERROR:
                task.start();
                break;
            case Progress.LOADING:
                task.pause();
                break;
            case Progress.FINISH:
//                    if (ApkUtils.isAvailable(context, new File(progress.filePath))) {
//                        ApkUtils.uninstall(context, ApkUtils.getPackageName(context, progress.filePath));
//                    } else {
//                        ApkUtils.install(context, new File(progress.filePath));
//                    }
                break;
        }

        refresh(progress);
    }


    public void showProgress(String message) {
        if (hud == null) {
            hud = KProgressHUD.create(this)
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                    .setLabel(message)
                    .setCancellable(true);
        }
        if (!hud.isShowing()) {
            hud.show();
        }
    }

    public void hideProgress() {
        if (hud != null && hud.isShowing()) {
            hud.dismiss();
        }
    }


    /**
     * 调用ShareSDK执行分享
     *
     * @param context
     * @param platformToShare 指定直接分享平台名称（一旦设置了平台名称，则九宫格将不会显示）
     * @param showContentEdit 是否显示编辑页
     */
    public void share(Context context, String platformToShare, boolean showContentEdit) {

        if (!UtilTools.LoginJudge()) {
            CustomToast.INSTANCE.showToast("请先登录");
            return;
        }

        OnekeyShare oks = new OnekeyShare();
        oks.setSilent(!showContentEdit);
        if (platformToShare != null) {
            oks.setPlatform(platformToShare);
        }
        //ShareSDK快捷分享提供两个界面第一个是九宫格 CLASSIC  第二个是SKYBLUE
        oks.setTheme(OnekeyShareTheme.CLASSIC);
        // 在自动授权时可以禁用SSO方式
        oks.disableSSOWhenAuthorize();
        //oks.setAddress("12345678901"); //分享短信的号码和邮件的地址
        oks.setTitle(mAllData.getTitle());
        oks.setTitleUrl(mAllData.getVideo_share_url());
        oks.setText(mAllData.getIntro());
        //oks.setImagePath("/sdcard/test-pic.jpg");  //分享sdcard目录下的图片
        oks.setImageUrl(mAllData.getCover());
        oks.setUrl(mAllData.getVideo_share_url()); //微信不绕过审核分享链接
//        oks.setFilePath(testVideo);  //filePath用于视频分享
//        oks.setComment(context.getString(R.string.app_share_comment)); //我对这条分享的评论，仅在人人网和QQ空间使用，否则可以不提供
        //QZone分享完之后返回应用时提示框上显示的名称
//        oks.setSite("ShareSDK");
//        oks.setSiteUrl("http://mob.com");//QZone分享参数
//        oks.setVenueName("ShareSDK");
//        oks.setVenueDescription("This is a beautiful place!");
//        oks.setLatitude(23.169f);
//        oks.setLongitude(112.908f);
        // 将快捷分享的操作结果将通过OneKeyShareCallback回调
        // oks.setCallback(new OneKeyShareCallback());
        // 去自定义不同平台的字段内容
        // oks.setShareContentCustomizeCallback(new
        // ShareContentCustomizeDemo());
        // 在九宫格设置自定义的图标
//        Bitmap logo = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher);
//        String label = "ShareSDK";
//        View.OnClickListener listener = new View.OnClickListener() {
//            public void onClick(View v) {
//
//            }
//        };
//        oks.setCustomerLogo(logo, label, listener);

        // 为EditPage设置一个背景的View
        //oks.setEditPageBackground(getPage());
        // 隐藏九宫格中的新浪微博
        // oks.addHiddenPlatform(SinaWeibo.NAME);

        // String[] AVATARS = {
        // 		"http://99touxiang.com/public/upload/nvsheng/125/27-011820_433.jpg",
        // 		"http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339485237265.jpg",
        // 		"http://diy.qqjay.com/u/files/2012/0523/f466c38e1c6c99ee2d6cd7746207a97a.jpg",
        // 		"http://diy.qqjay.com/u2/2013/0422/fadc08459b1ef5fc1ea6b5b8d22e44b4.jpg",
        // 		"http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339510584349.jpg",
        // 		"http://diy.qqjay.com/u2/2013/0401/4355c29b30d295b26da6f242a65bcaad.jpg" };
        // oks.setImageArray(AVATARS);              //腾讯微博和twitter用此方法分享多张图片，其他平台不可以

        // 启动分享
        oks.show(context);
    }


//
//    SelectFaceHelper.OnFaceOprateListener mOnFaceOprateListener = new SelectFaceHelper.OnFaceOprateListener() {
//        @Override
//        public void onFaceSelected(SpannableString spanEmojiStr) {
//            if (null != spanEmojiStr) {
//                mEditMessageEt.append(spanEmojiStr);
//            }
//        }
//
//        @Override
//        public void onFaceDeleted() {
//            int selection = mEditMessageEt.getSelectionStart();
//            String text = mEditMessageEt.getText().toString();
//            if (selection > 0) {
//                String text2 = text.substring(selection - 1);
//                if ("]".equals(text2)) {
//                    int start = text.lastIndexOf("[");
//                    int end = selection;
//                    mEditMessageEt.getText().delete(start, end);
//                    return;
//                }
//                mEditMessageEt.getText().delete(selection - 1, selection);
//            }
//        }
//
//    };
//
//    View.OnClickListener faceClick = new View.OnClickListener() {
//        @Override
//        public void onClick(View v) {
//
//
//            if (null == mFaceHelper) {
//                mFaceHelper = new SelectFaceHelper(SubscribeDeteilsActivity.this, addFaceToolView);
//                mFaceHelper.setFaceOpreateListener(mOnFaceOprateListener);
//            }
//            if (isVisbilityFace) {
//                isVisbilityFace = false;
//                addFaceToolView.setVisibility(View.GONE);
//            } else {
//                isVisbilityFace = true;
//                addFaceToolView.setVisibility(View.VISIBLE);
//                hideInputManager(SubscribeDeteilsActivity.this);
//            }
//        }
//    };
//    View.OnClickListener sendClick = new View.OnClickListener() {
//        @Override
//        public void onClick(View v) {
//            String msg = mEditMessageEt.getText().toString();
//            if (msg.equals("")) {
//                return;
//            }
//            String msgStr = ParseEmojiMsgUtil.convertToMsg(mEditMessageEt.getText(), SubscribeDeteilsActivity.this);// 这里不要直接用mEditMessageEt.getText().toString();
//            sendPingLun(msgStr);
//            mEditMessageEt.setText("");
//        }
//    };

    // 隐藏软键盘
    public void hideInputManager(Context ct) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        boolean isOpen = imm.isActive();//isOpen若返回true，则表示输入法打开
        if (isOpen) {
            imm.hideSoftInputFromWindow(dialog_edittext.getWindowToken(), 0); //强制隐藏键盘
        }
    }

    public void showInputManager(Context ct) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(dialog_edittext,InputMethodManager.SHOW_FORCED);
    }


    /**
     * 相关推荐的水平滚动类
     */
    class XiangGuanTuiJianAdapter extends RecyclerView.Adapter {


        List<TuiJianVideoModel.ResultBean.DataBean> mAdsBeanList = new ArrayList<>();
        Context mContext;

        public XiangGuanTuiJianAdapter(List<TuiJianVideoModel.ResultBean.DataBean> adsBeanList, Context context) {
            mAdsBeanList = adsBeanList;
            mContext = context;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            final Holder h = new Holder(LayoutInflater.from(parent.getContext()).inflate(R.layout.video_player_tuijian_item, parent, false));

            return h;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            PicassoUtils.loadImageView(mContext, mAdsBeanList.get(position).getCover(), ((Holder) holder).iv);

            ((Holder) holder).iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {





                    TuiJianVideoModel.ResultBean.DataBean m = mAdsBeanList.get(position);
                    VideoPlayerPostModel model = new VideoPlayerPostModel();
                    model.setMultimedia_id(m.getMultimedia_id());
                    model.setTitle(m.getTitle());
                    model.setIntro(m.getIntro());
                    model.setCover(m.getCover());
                    model.setDuration(m.getDuration());
                    model.setPublish_at(m.getPublish_at());
                    model.setPlay_url(m.getPlay_url());
                    model.setType(m.getType());
                    model.setPlay_count(m.getPlay_count());
                    model.setComment_count(m.getComment_count());
                    model.setLike_count(m.getLike_count());
                    model.setCollection_count(m.getCollection_count());
                    model.setStatus(m.getStatus());
                    model.setCreated_at(m.getCreated_at());
                    model.setUpdated_at(m.getUpdated_at());
                    model.setIs_collectied(m.getIs_collectied());
                    model.setIs_like(m.getIs_like());
                    model.setVideo_share_url(m.getVideo_share_url());
                    VideoPlayerPostModel.AlbumBean albumBean = new VideoPlayerPostModel.AlbumBean();
                    albumBean.setAlbum_id(m.getAlbum().getAlbum_id());
                    albumBean.setName(m.getAlbum().getName());
                    albumBean.setCover(m.getAlbum().getCover());
                    albumBean.setIs_order(m.getAlbum().getIs_order());
                    model.setAlbum(albumBean);

                    Intent intent2 = new Intent(mContext, SubscribeDeteilsActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("data",model);
                    intent2.putExtras(bundle);
                    intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(intent2);
                    finish();
                }
            });
        }

        @Override
        public int getItemCount() {

            return mAdsBeanList == null || mAdsBeanList.size() == 0 ? 0 : mAdsBeanList.size();
        }


        class Holder extends RecyclerView.ViewHolder {

            ImageView iv;

            public Holder(View itemView) {
                super(itemView);

                iv = (ImageView) itemView.findViewById(R.id.imageView);
            }
        }
    }


    private class ListDownloadListener extends DownloadListener {


        ListDownloadListener(Object tag, AlbumVideoBatchDownloadAllManagerAdapter.ViewHolder holder) {
            super(tag);
        }

        @Override
        public void onStart(Progress progress) {
        }

        @Override
        public void onProgress(Progress progress) {
        }

        @Override
        public void onError(Progress progress) {
            Throwable throwable = progress.exception;
            if (throwable != null) throwable.printStackTrace();
        }

        @Override
        public void onFinish(File file, Progress progress) {
            CustomToast.INSTANCE.showToast("下载完成");
        }

        @Override
        public void onRemove(Progress progress) {
        }
    }


}


